package com.coolwen.controller;

import com.coolwen.entity.SccocerException;
import com.coolwen.entity.Team;
import com.coolwen.entity.User;
import com.coolwen.service.TeamService;
import com.coolwen.service.UserService;
import com.coolwen.service.UserTeamService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.List;

/**
 * Created by user on 2016-11-23.
 */
@Controller
@SessionAttributes("loginUser")
public class IndexController {
    /**
     * 引入log4j,进行日志打印
     */
    private static final Logger LOGGER = Logger.getLogger(IndexController.class);
    /**
     * 引入User,Team,UserTeam的service,方便调用方法
     */
    @Autowired
    UserService userService;

    @Autowired
    TeamService teamService;

    @Autowired
    UserTeamService userTeamService;

    /**
     * 跳转到登录界面
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 用户登录方法
     *
     * @param username
     * @param password
     * @param model
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, Model model) {
        User u = userService.findUserByUserName(username);
        /*判断登录信息是否正确*/
        if ("".equals(username) || "".equals(password)) {
            throw new SccocerException("你的输入不完整！");
        }
        if (u == null || !password.equals(u.getUserPassword())) {
            throw new SccocerException("用户名或者密码错误");
        }
        model.addAttribute("loginUser", u);
        /*如果该用户没有属于自己的球队，则跳往添加球队的页面*/
        if (userTeamService.findUserTeamByUserID(u.getUserId()) == null)

        {
            return "redirect:/team/team/addTeam";
        }
        //todo 需要写主页
        /*登录成功，跳转到首页*/
        return "redirect:/";
    }


    /**
     * 在首页显示所有队伍的信息
     *
     * @param model
     * @return
     */

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String listAllTeam(Model model) {
        /*获取所有队伍的信息*/
        List<Team> teams = teamService.findAllTeam();
        model.addAttribute("teams", teams);
        return "challenge/challengeindex";
    }


}
